package com.jly.exception;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.jly.vos.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Liwenhao
 * @date 2022/3/23 15:37
 * @description
 */
@Slf4j
@ControllerAdvice
public class CommonExceptionHandler {

    /**
     *  处理接口层报错
     * @param ex
     * @return
     */
    @ExceptionHandler(APIException.class)
    @ResponseBody
    public ApiResult validateHandler(APIException ex) {
        return ApiResult.fail(ex.getMessage());
    }

    /**
     * 处理业务层报错
     * @param ex
     * @return
     */
    @ExceptionHandler(BIZException.class)
    @ResponseBody
    public ApiResult validateHandler(BIZException ex) {
        log.error(ex.getMsg(),ex);
        ex.printStackTrace();
        return ApiResult.fail(ex.getMessage());
    }

    /**
     * 处理参数校验异常错误
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiResult validateHandler(MethodArgumentNotValidException ex) {
        log.error(ex.getMessage(), ex);
        return process(ex.getBindingResult());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public ApiResult validateHandler(IllegalArgumentException ex) {
        log.error(ex.getMessage(), ex);
        return ApiResult.fail(ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ApiResult exceptionHandle(Exception ex) {
        log.error(ex.getMessage(), ex);
        return ApiResult.fail(ex.getMessage());
    }

    private ApiResult<List<String>> process(BindingResult result) {
        List<String> errorMessages = new ArrayList<>();
        for (FieldError fieldError : result.getFieldErrors()) {
            String error = String.format("field: %1$s, error message: %2$s", fieldError.getField(),
                fieldError.getDefaultMessage());
            log.error(error);
            errorMessages.add(error);
        }
        ApiResult<List<String>> apiResult = new ApiResult<>();
        apiResult.setSuccess(false);
        apiResult.setCode("400");
        apiResult.setMessage("Validation Failed");
        apiResult.setData(errorMessages);
        return apiResult;
    }
}
